<template>
  <div class="main">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
    <el-form-item label="提交时间" prop="submitTimeList">
        <el-date-picker
            v-model="queryParams.submitTimeList"
            type="datetimerange"
            range-separator="至"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            start-placeholder="开始日期"
            size="small"
            @keyup.enter.native="handleQuery"
            end-placeholder="结束日期">
        </el-date-picker>
    </el-form-item>
    <el-form-item label="提交人" prop="createBy">
        <el-input
            v-model="queryParams.createBy"
            placeholder="请输入提交人"
            clearable
            size="small"
            style="width:200px"
        />
    </el-form-item>
    <el-form-item label="流程状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
            <el-option
                v-for="item in dict.type.act_status"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
        </el-select>
    </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登录账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="(如zhangsan)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入用户邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :height="height"
              :data="humanEntryList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="提交时间" align="center" prop="actBusinessStatus.createTime" width="180px" sortable/>
      <el-table-column label="提交人" align="center" prop="actBusinessStatus.createBy" width="180px" sortable/>
<!--      <el-table-column label="主键" align="center" prop="id" v-if="false"/>-->
      <el-table-column label="姓名" align="center" prop="userName" sortable/>
      <el-table-column label="性别" align="center" prop="sex" sortable >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="别名" align="center" prop="otherName" sortable/>-->
      <el-table-column label="账号" align="center" prop="nickName" sortable/>
      <el-table-column label="用户邮箱" align="center" prop="email" sortable/>
      <el-table-column label="手机号码" align="center" prop="phonenumber" sortable/>
    <el-table-column label="流程状态" align="center" prop="actBusinessStatus.status" sortable >
        <template slot-scope="scope">
            <dict-tag :options="dict.type.act_status" :value="scope.row.actBusinessStatus.status"/>
        </template>
    </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.actBusinessStatus.status==='draft'||scope.row.actBusinessStatus.status==='back'||scope.row.actBusinessStatus.status==='cancel'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="(scope.row.actBusinessStatus.status==='draft' || scope.row.actBusinessStatus.status==='cancel' || scope.row.actBusinessStatus.status==='back') && (scope.row.createBy === userId || userId === 'admin' || userId === 'sysadmin')"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
            <el-button
                v-if="scope.row.actBusinessStatus.status==='waiting'"
                size="mini"
                type="text"
                icon="el-icon-back"
                @click="cancelProcessApply(scope.row)"
            >撤销</el-button>
            <el-button
                v-if="scope.row.actBusinessStatus.status!=='draft' || scope.row.actBusinessStatus.status==='cancel' || scope.row.actBusinessStatus.status==='back'"
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
            >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改录用申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :before-close="cancel">
    <el-tabs  type="border-card" >
      <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" inline :rules="rules" >
            <el-form-item label="编号" prop="number">
                <el-input  v-model="form.numberNum" disabled style="width: 280px;"/>
            </el-form-item>
            <el-form-item label="是否为经理级别" prop="isManage" >
              <el-select v-model="form.isManage" :disabled='isdisabled' placeholder="请选择">
                <el-option
                  v-for="item in optionList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
<!--              <el-input  v-model="form.numberNum" disabled style="width: 280px;"/>-->
            </el-form-item>
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="form.nickName" :disabled='isdisabled' placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="form.sex" :disabled='isdisabled' placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
<!--            <el-form-item label="别名" prop="otherName">-->
<!--              <el-input v-model="form.otherName" :disabled='isdisabled' placeholder="请输入别名" />-->
<!--            </el-form-item>-->
            <el-form-item label="账号" prop="userName">
              <el-input v-model="form.userName" :disabled='isdisabled' placeholder="(如zhangsan)" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" :disabled='isdisabled' placeholder="请输入密码" />
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="form.email" :disabled='isdisabled' placeholder="请输入用户邮箱" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber"
                        @input="form.phonenumber=form.phonenumber.replace(/^\D*([0-9]\d*)?.*$/,'$1')"
                        :disabled='isdisabled' placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
            <el-form-item label="部门" prop="departId">
              <el-select v-model="form.departId"
                         style="width: 3.55rem"
                         :disabled='isdisabled'
                         @change="deptChange"
                         placeholder="请选择" clearable>
                <el-option
                  v-for="item in deptList"
                  :key="item.deptName"
                  :label="item.deptName"
                  :value="item.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="form.roleIds"
                         :disabled='isdisabled'
                         multiple placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
<!--              <el-input v-model="form.roleId" :disabled='isdisabled' placeholder="请输入角色" />-->
            </el-form-item>
<!--            <el-form-item label="绑定员工信息" prop="oaEmployeeName" >-->
<!--              <el-input v-model="form.oaEmployeeName" readonly :disabled='isdisabled' placeholder="请输入" >-->
<!--                <el-button type="primary" slot="append" @click="openUserSelect" v-text="btnText"></el-button>-->
<!--                <el-button type="success" slot="append" @click="clearSelect">清空</el-button>-->
<!--              </el-input>-->
<!--&lt;!&ndash;              <el-input v-model="form.oaEmployeeId" :disabled='isdisabled' placeholder="请输入花名册id" />&ndash;&gt;-->
<!--            </el-form-item>-->
            <div>
              <el-form-item label="合同附件" v-if="!(isdisabled&&!form.attachment)">
                <file-upload v-model="form.attachment" :isDisabled='isdisabled' :limit="5"/>
              </el-form-item>
            </div>
          </el-form>
          <div class="dialog-footer" style="float:right" v-if="flag">
            <el-button :loading="buttonLoading" type="info" @click="submitForm('zancun')">暂存</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')">提交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
      </el-tab-pane>
      <!-- 审批历史 -->
      <el-tab-pane label="审批历史" v-if="processInstanceId">
            <history ref="historyRef" :processInstanceId="processInstanceId" ></history>
      </el-tab-pane>
    </el-tabs>
    </el-dialog>
    <employee ref="employee" @confirmUser="clickUser" :propUser="propUser"></employee>
      <!-- 提交 -->
      <verify ref="verifyRef"
              @submitCallback="submitCallback"
      :componentName="componentName" :taskId="taskId" :taskVariables="taskVariables" :sendMessage="sendMessage"></verify>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import { listHumanEntry, getHumanEntry, delHumanEntry, addHumanEntry, updateHumanEntry } from "@/api/oa/humanEntry";
import processApi from "@/api/workflow/processInst";
import history from "@/components/Process/History";
import verify from "@/components/Process/Verify";
import {parseTime} from "@/utils/ruoyi";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listAll, selectAllSonData} from "@/api/system/dept";
import employee from "@/views/components/user/employee.vue";
export default {
  name: "HumanEntry",
  dicts: ['act_status','sys_user_sex'],
  components: {
    Treeselect,
      history,
      verify,
    employee,
  },
props:{
},
  data() {
    return {
      componentName: "录用申请",
      btnText:"选择",
      isdisabled:false,
      // 流程实例
      processInstanceId: '',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 录用申请表格数据
      humanEntryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        submitTimeList: [],
        createBy:'',
        status:'',
        userName: undefined,
        nickName: undefined,
        email: undefined,
        phonenumber: undefined,
      },
      // 部门树选项
      deptOptions: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "账号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "用户邮箱不能为空", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" }
        ],
        departId: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ],
        roleId: [
          { required: true, message: "角色不能为空", trigger: "blur" }
        ],
        oaEmployeeId: [
          { required: true, message: "花名册id不能为空", trigger: "blur" }
        ],
      },
      height:`calc(100% - 88px)`,
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {},
      processKey: 'oa_human_entry',
      userId:'',
      roleOptions:[],
      deptList:[],
      propUser:"",
      optionList:[
        {
        label:"是",
        value:"1"
        },
        {
          label:"否",
          value:"0"
        }
      ]
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getUser();
  },
  mounted() {
      this.$nextTick(() => {
        let formHeight = this.$refs.queryForm.$el.offsetHeight;
        this.height = `calc(100% - ${formHeight}px - 88px)`;
      },300)
      window.onresize = () => {
        let formHeight = this.$refs.queryForm.$el.offsetHeight;
        this.height = `calc(100% - ${formHeight}px - 88px)`;
      };
      this.userId=this.$store.state.user.name;

  },
  methods: {
    /** 查询录用申请列表 */
    getList() {
      this.loading = true;
      listHumanEntry(this.queryParams).then(response => {
        this.humanEntryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.selectAllSonData();
    },
    // 取消按钮
    cancel() {
      this.isdisabled=false
      this.open = false;
      this.reset();
    },
    deptChange(val){
      let depart=this.deptList.filter(item =>item.deptId==val);
      if (depart.length>0){
        this.form.departName=depart[0].deptName;
      }else {
        this.form.departName='';
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        isManage:undefined,
        deptId: undefined,
        userId: undefined,
        userName: undefined,
        // otherName: undefined,
        nickName: undefined,
        password: undefined,
        email: undefined,
        phonenumber: undefined,
        departId: undefined,
        departName:undefined,
        roleId: undefined,
        oaEmployeeId: undefined,
        createBy: undefined,
        updateBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        oaEmployeeName:undefined,
      };
      this.processInstanceId = undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
       this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      if (selection.length==1){
          if (selection[0].actBusinessStatus.status=='draft'||selection[0].actBusinessStatus.status=='back'||selection[0].actBusinessStatus.status=='cancel'){
             }else {
              this.single=true;
          }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.flag = true
      this.reset();
      this.open = true;
      this.title = "添加录用申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.flag = true
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getHumanEntry(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.departId=Number(this.form.departId);
        this.form.roleIds = this.form.roleId.split( ',' ).map(item => Number(item));
        // this.$set(this.form,'roleIds',this.form.roleId.split( ',' ))
        this.$forceUpdate()
        if (response.data.actBusinessStatus.createTime){
            this.form.numberNum=this.processKey + '@' + parseTime(response.data.actBusinessStatus.createTime, '{y}{m}{d}{h}{i}{s}')
        }
        this.$nextTick(() => {
            this.processInstanceId=response.data.actBusinessStatus.processInstanceId
        })
        this.open = true;
        this.title = "修改录用申请";

      });
    },
    //查看
    handleView(row){
        this.flag = false
        this.loading = true;
        this.reset();
        const id = row.id || this.ids
        getHumanEntry(id).then(response => {
          this.loading = false;
          this.form = response.data;
          this.form.departId=Number(this.form.departId);
          this.form.roleIds = this.form.roleId.split( ',' ).map(item => Number(item));
          if (response.data.actBusinessStatus.createTime){
                this.form.numberNum=this.processKey + '@' + parseTime(response.data.actBusinessStatus.createTime, '{y}{m}{d}{h}{i}{s}')
            }
            this.$nextTick(() => {
                this.processInstanceId=response.data.actBusinessStatus.processInstanceId
            })
            this.isdisabled=true
            this.open = true;
            this.title = "查看录用申请业务";
        });
    },
    /** 提交按钮 */
    submitForm(flag) {
      this.form.roleId=this.form.roleIds.join(",");
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          // this.form.roleId=this.form.roleIds.join(",");
          // et resultAssignee = arrAssignee.join(",")
          if (this.form.id != null) {
            updateHumanEntry(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              if(flag === 'submit'){
                  this.submitFormApply(response.data)
              }else {
                  this.open = false;
              }
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addHumanEntry(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              if(flag === 'submit'){
                this.submitFormApply(response.data)
              }else {
                this.open = false;
                this.cancel();
              }
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 提交成功回调
    submitCallback(){
        this.open = false;
        this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除录用申请编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delHumanEntry(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    test123(){
      console.log(this.form)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/humanEntry/export', {
        ...this.queryParams
      }, `humanEntry_${new Date().getTime()}.xlsx`)
    },
    //提交流程
    submitFormApply(entity){
        //流程变量
        this.taskVariables = {
            entity: entity,
            maximumValue:this.maximumValue,
            isManage:this.form.isManage
        }
        console.log(this.taskVariables)
        const data = {
            processKey: this.processKey, // key
            businessKey: entity.id, // 业务id
            variables: this.taskVariables,
            classFullName: 'com.ruoyi.oa.domain.OaPurchaseParity'
        }
        this.sendMessage = {
        title: "录用申请",
        messageContent: this.$store.state.user.nickName + "提交了录用申请"
      };
        // 启动流程
        processApi.startProcessApply(data).then(response => {
            this.taskId = response.data.taskId;
            this.$refs.verifyRef.visible = true
            this.$refs.verifyRef.reset()
        })
    },
    //撤回
    cancelProcessApply(row){
        this.$modal.confirm('是否撤销申请').then(() => {
        this.loading = true;
        return processApi.cancelProcessApply(row.actBusinessStatus.processInstanceId);
        }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
        }).finally(() => {
        this.loading = false;
        });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getUser(){
      getUser().then(response => {
        this.roleOptions = response.data.roles;
      });
    },
    selectAllSonData(){
      selectAllSonData().then(res=>{
        console.log(res.data)
        this.deptList=res.data;
      })
    },

    openUserSelect(){
      this.propUser = "";
      if(this.form.oaEmployeeId){
        let userIds =  this.form.oaEmployeeId;
        if(userIds.length>0){
          this.propUser = userIds
        }
      }
      this.$refs.employee.visible=true;
    },
    clearSelect(){
      this.form.oaEmployeeName="";
      this.form.oaEmployeeId="";
      // this.form.department="";
    },
    clickUser(userList){
      let arrAssignee= userList.map(item => {
        return item.name
      })
      let arrAssigneeId= userList.map(item => {
        return item.id
      })
      let resultAssignee = arrAssignee.join(",")
      let resultAssigneeId = arrAssigneeId.join(",")
      this.$set(this.form,'oaEmployeeName',resultAssignee)
      this.$set(this.form,'oaEmployeeId',resultAssigneeId)
      this.$refs.employee.visible = false
      this.$forceUpdate()
    }
  }
};
</script>
<style scoped>
    .main{
      height: 100%;
    }
    /* 设置滚动条宽度和高度 */
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
        width: 8px; /* 横向滚动条 */
        height: 8px; /* 纵向滚动条 必写 */
    }
    /* 设置滚动条样式 */
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
        background-color: #dde;
        border-radius: 3px;
    }
    #selectForm >>> .el-form-item__label {
        font-size: 12px;
    }
    ::v-deep .bjsm .el-form-item__content{
        width: calc(100% - 130px) !important;
    }
</style>
